/**
 * @author taojiang
 * @since 2013-10-24
 */
Ext.onReady(function() {
	
 	//年度
	var icYearSelectStore = new Ext.data.Store({
			restful: true,
	    autoLoad: true,
	    proxy: new Ext.data.HttpProxy({
	        url: basePath + '/auditYear.json'
	    }),
	    reader: new Ext.data.JsonReader({
	        root: 'json.data'
	    },
	    ['ID', 'AUDIT_YEAR'])

	});
	icYearSelectStore.load();
	
	var icYearSelect = new Ext.form.ComboBox({
	    id: 'icYear',
	    name: 'icYear',
	    hiddenName:"yearId",
	    fieldLabel: '选择年度',
	    triggerAction: 'all',
	    store : icYearSelectStore,
	    displayField: 'AUDIT_YEAR',
	    valueField: 'ID',
	    mode: 'local',
	    forceSelection: true,
	    typeAhead: true,
	    emptyText: '请选择',
	    resizable: true,
	    anchor: '100%'
	    
	});

	 var store = new Ext.data.Store({
			restful:true,	
	        proxy : new Ext.data.HttpProxy({url:basePath+'/icYearQueryAction.json'}),
	        reader: new Ext.data.JsonReader({
	        	totalProperty : 'json.count',
	        	root:'json.data'
	        }, [
				{name: 'id',mapping :'ID'},
				{name: 'date_id',mapping :'DATE_ID'},
				{name: 'creator',mapping :'CREATOR'},
				{name: 'creatdate',mapping : 'CREATDATE'},
				{name: 'is_cal',mapping : 'IS_CAL'}				
			])
		});
	 //复选
    var sm = new Ext.grid.CheckboxSelectionModel({singleSelect :true});
	// 定义自动当前页行号
	var rownum = new Ext.grid.RowNumberer({
				header : '序号',
				width : 40
			});
	
	// 定义列模型
	var cm = new Ext.grid.ColumnModel([sm,rownum, 
	                                {header : 'id',dataIndex : 'id',width : 80,sortable : true,hidden:true},
                                    {header : '主题',dataIndex : 'date_id',width:120,sortable:true,renderer:
                                    	function(value, cellmeta, record, rowIndex, columnIndex, store){
	                                	 	var i = icYearSelectStore.getCount();
	                                	 	var text='';
	                                	 	if (icYearSelectStore.query('ID', value).length == 1) {
	                                	 		text = icYearSelectStore.query('ID', value).get(0).get("AUDIT_YEAR");
	                        				}
	                                	 	return '<a href=icSystem.jsp?date_id='+value+'>'+text+'年'+'</a>';
	                                	  }}
                    
                                  
	                       			   ]);
		// 每页显示条数下拉选择框
		var pagesize_combo = new Ext.form.ComboBox({
			name : 'pagesize',
			triggerAction : 'all',
			mode : 'local',
			store : new Ext.data.ArrayStore({
				fields : [ 'value', 'text' ],
				data : [ [ 10, '10条/页' ], [ 20, '20条/页' ], [ 50, '50条/页' ],
							[ 100, '100条/页' ], [ 250, '250条/页' ],
							[ 500, '500条/页' ] ]
			}),
			valueField : 'value',
			displayField : 'text',
			value : '20',
			resizable : true,
			width : 85
		});


		// 改变每页显示条数reload数据
		pagesize_combo.on("select", function(comboBox) {
			bbar.pageSize = parseInt(pagesize_combo.getValue()),
			store.reload({
				params : {
					start : 0,
					limit : parseInt(pagesize_combo.getValue())
				}
			});
		});
		// 分页工具栏
		var bbar = new Ext.PagingToolbar({
			pageSize : parseInt(pagesize_combo.getValue()),
			store : store,
			displayInfo : true,
			displayMsg : '显示{0}条到{1}条,共{2}条',
			emptyMsg : "没有符合条件的记录",
			items : [ '-', '&nbsp;&nbsp;', pagesize_combo ]
		});
		
		var menubar = [{
        	text: '新增',
        	iconCls: 'addIconCss',
        	handler: function() {
        		addIcYearWindow.show();
        	}
    },'-',{
        	text: '复制',
        	iconCls: 'editIconCss',
        	handler: function() {
        		 var selectLength = listPanel.getSelectionModel().getSelections().length;
        		  if (selectLength != 1) {
                      Ext.Msg.alert('提示', '请选择一条记录!');
                      return;
                  } 
        		  addwindow.show();
        		  for (var i = 0; i < selectLength; i++) {
                      selectRe = listPanel.getSelectionModel().getSelections()[i];
                      tempId = selectRe.data.ID;
                      tempName = selectRe.data.NAME;
                      tempContent = selectRe.data.CONTENT;
                      tempRiskLevel = selectRe.data.RISK_LEVEL_DICT;
                      frequence2 = selectRe.data.FREQUENCE;
                      businessDict = selectRe.data.BUSINESS_DICT;
                    //  alert(tempId+","+tempName+","+tempContent+","+tempRiskLevel);
                      Ext.getCmp('problemsDictId').setValue(tempId);
                      Ext.getCmp('problemsDictName').setValue(tempName);
                      Ext.getCmp('riskLevel').setValue(tempRiskLevel);
                      Ext.getCmp('frequence2').setValue(frequence2);
                      Ext.getCmp('business').setValue(businessDict);
                      Ext.getCmp('content').setValue(selectRe.data.CONTENT);
                  }
        		
            	
        	}
    },'-',{
    	text: '删除',
    	iconCls: 'deleteIconCss',
    	handler: function() {
    		 var selectLength = listPanel.getSelectionModel().getSelections().length;
             var selectRe;
             var tempId;
             var idStr = '';
             if (selectLength < 1) {
                 Ext.Msg.alert('提示', '请选择需要删除的记录!');
                 return;
             } 
             for (var i = 0; i < selectLength; i++) {
                 selectRe = listPanel.getSelectionModel().getSelections()[i];
                 tempId = selectRe.data.id;
                 idStr += tempId;
                 if (i != selectLength - 1) idStr += ',';
             }
             Ext.MessageBox.confirm('提示', '确定删除吗?',
                     function(buttonId) {
                         if (buttonId.toLowerCase() == "no") {
                             return;
                         }
                         Ext.Ajax.request({
                             url: basePath + '/icYearAction!destroy.json',
                             mothed: 'POST',
                             params: {
                                 'idStr': idStr
                             },
                             success: function(response) {
                            	 store.reload();
                                 Ext.Msg.alert('提示', '操作成功');
                             },
                             failure: function(response) {
                                 Ext.Msg.alert('提示', '操作失败'
                                 /*response.responseText*/
                                 );
                             }
                         });
             			}
             );
    	}
    	
    }];

 	var listPanel = new Ext.grid.GridPanel(
				{
					id : 'listPanel',
					//title : "问题词条列表",
					height:document.body.clientHeight-100,
					region : 'center',
					store : store,
					frame : true,
					stripeRows : true,
					layout:'fit',
					cm : cm,
					sm : sm,
					bbar : bbar,// 分页工具栏
					tbar :menubar,
					viewConfig : {
						forceFit: true

					// 不产横向生滚动条, 各列自动扩展自动压缩, 适用于列数比较少的情况
					},
					loadMask : {
						msg : '正在加载表格数据,请稍等...'
					}
				});
 	store.load();
 	listPanel.on('rowdblclick', function(gridPanel, rowIndex, e) {
    	var selectedId = store.data.items[rowIndex].id;  
    	alert(selectedId);
 	});
 

 	
 	/***新增 **/
 	var addIcYearPanel = new Ext.form.FormPanel({
		id:'addIcYearPanel',
	  	height: 120,
        width: 400,
        buttonAlign: 'center',
        labelWidth: 100,
        labelAlign: 'right',
        frame: true,
        autoScroll: true,
        region: 'north',
        split: true,
        items: [{
       	 layout: 'column',
       	 items:[{
       		 columnWidth: .9,
                layout: 'form',
                items:[icYearSelect]
                }]
       	 	
        }]
	});	
 	//window
 	var addIcYearWindow = new Ext.Window({
 		id:'addIcYearWindow',
	  	title: '新建年度内控评价体系',
        closable: true,
        closeAction: 'hide',
        width: 500,
        height: 150,
        minWidth: 300,
        minHeight: 250,
        layout: 'fit',
        plain: true,
        resizable: false,
        collapsible: false,
        draggable: false,
        border: false,
        autoScroll: true,
        closable: true,
        modal :true,
        animateTarget: Ext.getBody(),
        constrain: true,
        bodyStyle: 'padding:5px;',
        buttonAlign: 'center',
        items: addIcYearPanel,
        buttons: [{
            text: '保存', 
            handler: function(){
            	var icYear = Ext.getCmp('icYear').getValue();
            	if(icYear.length < 1){
            		showMessage('提示','请选择年度');
            		return false;
            	}
            	Ext.Ajax.request({
            		url: basePath + '/icYearAction!save.json',
                    mothed: 'POST',
                    params: {'icYear':icYear},
            		success: function (response){
            			addIcYearPanel.getForm().reset();
            			addIcYearWindow.hide();
            			showMessage("提示","操作成功");
            			store.load({
            				params : {
    	                        start : 0,
    	                        limit : bbar.pageSize
    	                     }
            			});
            		}
            	});
            	
            }					// The method to call when the save button is clicked.
        },{
            text: '关闭',
            handler: function(){
            	addIcYearWindow.hide();
            	addIcYearPanel.getForm().reset();
            }					// The method to call when the cancel button is clicked.
        }]
 		
 	});
 	 var viewport = new Ext.Viewport( {
         layout : 'fit',
         items : [ {
             layout : 'border',
             items : [{
                 region : 'center',
                 autoScroll : true,
                 id : 'center-panel',
                 margins : '0 0 0 0',
                 layout: 'fit',
                 items : [ listPanel ]
             } ]
         } ]
     });
	
});